﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HerGoS.ControlsUI;
using Ionic.Zip;
using HerGoS.Administration.Engine;
using System.IO;

namespace HerGoS.WebUI
{
    public partial class Update : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.BtnEnviar.Settings(new ButtonExtText());
            if (IsPostBack)
            {
                if (FileUpdate.HasFile)
                {
                    try
                    {
                        string filename = Path.GetFileName(FileUpdate.FileName);
                        string fullpath = Path.Combine(Path.GetTempPath(), filename);

                        if (File.Exists(fullpath))
                            File.Delete(fullpath);

                        FileUpdate.SaveAs(fullpath);

                        string folderName = "HergosUpdate";
                        string pathOrigen = Path.Combine(Path.GetTempPath(), folderName);

                        if (Directory.Exists(pathOrigen))
                            Directory.Delete(pathOrigen, true);

                        Directory.CreateDirectory(pathOrigen);

                        using (ZipFile zip = ZipFile.Read(fullpath))
                        {
                            zip.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
                            zip.ExtractAll(pathOrigen);
                        }
                        
                        GestorUpdate.Procesar(Path.Combine(pathOrigen, Path.GetFileNameWithoutExtension(filename)), Server.MapPath("."));


                        if (File.Exists(fullpath))
                            File.Delete(fullpath);

                        if (Directory.Exists(pathOrigen))
                            Directory.Delete(pathOrigen, true);
                        
                        MSJ.Text = "Proceso finalizado correctamente.";

                    }
                    catch (Exception ex)
                    {
                        MSJ.Text = "ERROR: El proceso finalizo con errores. <br/><br/>" + ex.Message;
                    }
                }
            }
        }
    }
}